<template>
  <div>
    <!-- 面包屑导航区域 -->
    <nav-bread name1="商品管理" name2="添加商品"></nav-bread>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert title="添加商品信息" type="info" show-icon center :closable="false"></el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tabs标签页 -->
      <el-form :model="goodsForm" :rules="goodsRules" ref="goodsFormRef" abel-position="top">
        <el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="beforeLeave" @tab-click="tabClick">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="goodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="goodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="goodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="goodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 商品分类级联选择框 -->
              <el-cascader v-model="goodsForm.goods_cat" clearable :options="goodsCateList" @change="goodsChange" :props="{ expandTrigger: 'hover' ,label:'cat_name',value:'cat_id',children:'children'}">
              </el-cascader>
            </el-form-item>

          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单的item项 -->
            <el-form-item :label="item.attr_name" v-for="item in manyParamsData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="value" v-for="(value,i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyParamsData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action表示图片要上传的后台api地址 -->
            <el-upload action="http://127.0.0.1:8888/api/private/v1/upload" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture" :headers="headerObj" :on-success="pictureRes">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="goodsForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="addGoodsBtn" @click="addClick">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

    </el-card>
    <!-- 商品图片对话框 -->
    <el-dialog title="图片预览" :visible.sync="picDialogVisible" width="60%">
     <img :src="PreviewPath" alt="">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      // 激活的step
      activeIndex: "0",
      // 商品表单对象
      goodsForm: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        pics: [],
        goods_introduce:'',
      },
      // 商品分类数据源
      goodsCateList: [],
      // 商品表单验证对象
      goodsRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
      // 获取的动态参数数据
      manyParamsData: [],
      // 获取的静态属性面板
      onlyParamsData: [],
      // 请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      // 图片URL地址
      PreviewPath: "",
      // 图片预览对话框
      picDialogVisible:false,
    };
  },
  created() {
    this.getCateList();
  },
  computed: {
    cateId() {
      return this.goodsForm.goods_cat[2];
    },
  },
  methods: {
    // 获取所有商品分类
    async getCateList() {
      const { data } = await this.$http.get("categories");
      if (data.meta.status !== 200)
        return this.$message.error("获取商品数据列表失败");
      this.goodsCateList = data.data;
    },
    beforeLeave(activeName, oldActiveName) {
      let a = true;
      if(oldActiveName==0){
        this.$refs.goodsFormRef.validate((valid) => {
        if (!valid) {
          this.$message.error("请先填写基本信息");
          a = false;
        }
      });
      }
      return a;
    },
    // tab栏切换事件
    async tabClick() {
      // 访问动态参数面板
      if (this.activeIndex === "1") {
        const { data } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "many" },
          }
        );
        if (data.meta.status !== 200) return;
        data.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(",");
        });
        console.log(data.data);
        this.manyParamsData = data.data;
      }
      // 访问静态属性面板
      if (this.activeIndex === "2") {
        const { data } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "only" },
          }
        );
        this.onlyParamsData = data.data;
        console.log(this.onlyParamsData);
      }
    },
    // 选择的不是三级清除
    goodsChange() {
      if (this.goodsForm.goods_cat.length !== 3) {
        this.goodsForm.goods_cat = [];
      }
    },
    // 处理图片预览
    handlePreview(file) {
      this.PreviewPath = file.response.data.url;
      this.picDialogVisible=true;
    },
    // 处理移除图片的操作
    handleRemove(file) {
      // 1、获取将要删除的图片路径
      const path = file.response.data.tmp_path;
      // 2、查找在表单的索引值
      const index = this.goodsForm.pics.findIndex((x) => {
        x.pic === path;
      });
      console.log(index);
      //  3、删除该图片
      this.goodsForm.pics.splice(index, 1);
    },
    // 图片上传成功时的钩子
    pictureRes(res) {
      //  拼接的到一个图片对象
      const pigInfo = { pic: res.data.tmp_path };
      this.goodsForm.pics.push(pigInfo);
      console.log(this.goodsForm.pics);
    },
    // 添加商品
    addClick(){
     this.$refs.goodsFormRef.validate(async valid=>{
       if(!valid)return this.$message.error('请先填写必要的信息');
      //  因为页面需要数组类型直接转换会报错，深拷贝原对象就行
      let goodsForm=_.cloneDeep(this.goodsForm)
       goodsForm.goods_cat=goodsForm.goods_cat.join(',')
      //  处理动态参数
          this.manyParamsData.forEach(item=>{
            let newInfo={
              attr_id:item.attr_id,
              attr_vals:item.attr_vals.join(',')
            };
            goodsForm.attrs=[];
            goodsForm.attrs.push(newInfo)
          });
      // 处理静态属性
           this.manyParamsData.forEach(item=>{
            let newInfo={
              attr_id:item.attr_id,
              attr_vals:item.attr_vals
            };
            goodsForm.attrs.push(newInfo)
          });
         const {data,}=await this.$http.post('goods',goodsForm);
         if(data.meta.status!==201)return this.$message.error(data.meta.msg);
         this.goodsForm.goods_introduce='';
         this.manyParamsData=[];
         this.onlyParamsData=[];
         this.$refs.goodsFormRef.resetFields();
         this.$message.success('创建商品成功');
         this.$router.push('/goods')
     })
    }
  },
};
</script>

<style lang="less" scoped>
.el-step {
  margin-top: 15px;
  margin-bottom: 15px;
}
.el-step__title {
  font-size: 13px !important;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.addGoodsBtn{
  margin-top: 15px;
}
</style>

